<template>
    <div class="earth-voice" v-if="isShowChat">
        <div class="voice-header">
            <p>{{ chatTitle }}</p>
            <div class="voice-icons">
                <div class="voice-delete">
                    <!-- <el-tooltip class="box-item" effect="light" content="删除对话记录" placement="top">
                        <el-icon :size="20" @click="deleteChat">
                            <Brush />
                        </el-icon>
                    </el-tooltip> -->
                </div>
                <div class="voice-delete" @click="closeChat">
                    <!-- <el-icon :size="20">
                        <Close />
                    </el-icon> -->
                </div>
            </div>
        </div>
    <!-- <div v-for="item in list" :key="item">{{ item }}</div> -->

        <!-- H5页面 -->
        <div class="voice-content">
            <div v-for="item in chatList" :key="item" ref="scrollItem">
                <div class="content-msg1" v-if="item.type == 'query'">
                    <div class="content-detail">
                        <p class="content-name">{{ item.name }} {{ dateFormat(new Date()) }}</p>
                        <p class="detail-query" v-dompurify-html="item.query"></p>
                    </div>
                    <img :src="item.img" />
                </div>
                <div class="content-msg" v-if="item.type == 'welcome'">
                    <img :src="item.img" />
                    <div class="content-detail">
                        <p class="content-name">{{ item.name }} {{ item.askTime }}</p>
                        <p class="detail-msg" v-for="el in item.contentList" :key="el.textResponse" v-dompurify-html="el.textResponse.includes('<') ? el.textResponse : markdownIt.render(el.textResponse)"
                            >
                        </p>
                        <div class="try-question" v-if="item.agentSuggestions"><img class="try-img"
                                src="../chat/tip.svg" alt="">试试这样问</div>

                        <div class="detail-tj" v-for="el in item.agentSuggestions" :key="el" @click="checkWel(el)"
                            v-dompurify-html="el.includes('<') ? el : markdownIt.render(el)">
                        </div>
                    </div>
                </div>
                <div class="demo-loading" v-if="item.type == 'anwserLoading'">正在加载中</div>
                <div class="content-msg" v-if="item.type == 'anwser'">
                    <img :src="imgUrl ? imgUrl : defaultImg" />
                    <div class="content-detail">
                        <p class="content-name">{{ item.name }} {{ item.askTime }}</p>
                        <div>
                            <p class="detail-msg" :class="item.isAgent ? 'detail-msg-active' : ''"
                                v-dompurify-html="item.textResponse">
                            </p>
                            <p v-if="item.isAgent" class="is-agent">* 内容由AI生成</p>
                        </div>
                    </div>
                </div>

                <div class="new-line" v-if="item.type == 'line'">
                    <p class="line"></p>
                    <p>以下是新对话</p>
                    <p class="line"></p>
                </div>
            </div>
        </div>
        <div class="voice-footer">
            <div class="add-chat">
                <el-tooltip class="box-item" effect="light" content="新增对话" placement="top">
                    <img src="../chat/newMsg.svg" alt="" srcset="" @click="addNewChat">

                </el-tooltip>
            </div>
            <el-input v-model.trim="chatDetail" placeholder="发送消息..." class="input-with-select" :disabled="!isFinish"
                ref="inputRef" @keydown.enter.exact="confirmChat">
                <template #append>
                    <img src="../chat/sendB.svg" alt="" @click="confirmChat">
                    <el-icon :size="20" @click="confirmChat" :color="chatDetail ? '#409efc' : '#ccc'">
                        <Promotion />
                    </el-icon>
                </template>
</el-input>
        </div>
        <!-- <h1>ahahahahahh</h1> -->
    </div>
    <!-- 图标 -->
    <img class="chat-show" src="../chat/chat.svg" alt="" @click="showAgentChat" v-if="!isShowChat">
    <!-- <p>{{ isShowChat }}</p> -->
</template>

<script setup>
import { agentChat } from '../http/api'
import { dateFormat } from '../utils'
import { onBeforeMount, ref, nextTick, watch, onMounted, onBeforeUnmount } from 'vue'
import MarkdownIt from 'markdown-it';
import myImg from '../chat/original.svg'
const markdownIt = new MarkdownIt();
const chatList = ref([])
const scrollItem = ref()
let chatDetail = ref('')
const imgUrl = ref('')
const imgUrl1 = 'https://p9-passport.byteacctimg.com/img/user-avatar/assets/e7b19241fb224cea967dfaea35448102_1080_1080.png~300x300.image'
let welcomeChat = ref()
// const urlParams = new URLSearchParams(window.location.href.split('?')[1])
// const agentParams = {}
// urlParams.forEach((value, key) => {
//     agentParams[key] = value;
// })
let desition = ref('')
let isAgent = ref(false)
let chatTitle = ref('')
const defaultImg = ref(myImg)
let isShowChat = ref(false)

let list = ref([111,222,333,444,555])

// 监听数据，页面自动滚动到最底部
watch(
    () => chatList.value,
    (newVal) => {
        nextTick(() => {
            scrollItem.value && scrollItem.value[newVal.length - 1].scrollIntoView(); // 关键代码
        });
    },
    {
        deep: true,
    }
);


watch(
    () => isShowChat.value,
    (newVal) => {
        nextTick(() => {
            console.log(newVal, 'watch');
        });
    },
    {
        deep: true,
    }
);

let isFinish = ref(true)
let sessionid = ''
// 发送消息
const confirmChat = async (type) => {
    if (!chatDetail.value || chatDetail.value == '') return
    if (isFinish.value == false) return
    isFinish.value = false
    const queryDetail = {
        type: 'query',
        query: chatDetail.value,
        img: imgUrl1,
        name: '我自己'
    }
    chatList.value.push(queryDetail)
    const params = {
        agentId: '75',
        start: false,
        query: chatDetail.value,
        sessionId: sessionid
    }
    chatList.value.push({ type: 'anwserLoading' })
    chatDetail.value = ''
    try {
        const data = await agentChat(params)
        chatList.value.pop()
        let resData = ''
        const response = contentOrLog(data.result)
        isAgent.value = isFinishType(data.result) == 'no' ? true : false
        const { contentList, askTime, sessionId } = data.result
        sessionid = sessionId
        let anwserDetail = {
            type: 'anwser',
            textResponse: '',
            img: imgUrl.value,
            name: chatTitle.value,
            askTime: askTime.slice(0, -4)
        }
        chatList.value.push(anwserDetail)
        if (response == 'ok') {
            resData = contentList[0].textResponse ? contentList[0].textResponse : '暂无数据，请稍后重试！'
        } else {
            resData = response
        }
        if (!resData.includes('<') && !(resData.includes('#') || resData.includes('*') || resData.includes('-'))) {
            resData = resData.replace(/\n/g, '<br>')
        } else {
            resData = resData.includes('<') ? resData : markdownIt.render(resData)
        }
        resData = resData.replace(/(\n)\1+/g, '$1')
        anwserDetail = {
            type: 'anwser',
            textResponse: resData,
            img: imgUrl.value,
            name: chatTitle.value,
            askTime: askTime.slice(0, -4),
            isAgent: isAgent.value
        }
        chatList.value.splice(chatList.value.length - 1, 1, anwserDetail);
        isFinish.value = true
    } catch (err) {
        console.log(err);
        chatList.value.pop()
        const anwserDetail = {
            type: 'anwser',
            textResponse: '系统繁忙，请稍后再试！',
            img: imgUrl.value,
            name: chatTitle.value,
            askTime: dateFormat(new Date())
        }
        isFinish.value = true
        chatList.value.push(anwserDetail)
    }

}


const showAgentChat = () => {
    nextTick(() => {
        isShowChat.value = !isShowChat.value
        console.log(isShowChat.value, 'own');
    })
    getWeldetail()
}
// 发送消息返回参数判断
const contentOrLog = (res) => {
    let a = ''
    const { agentLog } = res
    if (!agentLog) return 'ok'
    agentLog.forEach(el => {
        if (el.content.throught === 'RESPONSE' && el.content.response != '') {
            a = el.content.response
        } else {
            a = 'ok'
        }
    })
    return a
}

// 获取欢迎语
const getWeldetail = async () => {
    // const params = {
    //     agentId: '75',
    //     start: true
    // }
    // const chat = await agentChat(params)
    // const { result } = chat
    // chatTitle.value = result.agentDO.name
    // imgUrl.value = result.agentDO.icon
    // desition.value = result.agentDO.description
    // if (result.contentList && result.contentList.length == 0) return
    // welcomeChat.value = {
    //     type: 'welcome',
    //     agentSuggestions: result.agentSuggestions,
    //     askTime: result.askTime.slice(0, -4),
    //     contentList: result.contentList,
    //     img: imgUrl.value,
    //     name: result.agentDO.name
    // }
    welcomeChat.value = {
        type: 'welcome',
        agentSuggestions: ['你好啊' ],
        askTime: '2024-10-31 12:00',
        contentList: [{ textResponse: '# 你好啊' }],
        img: '',
        name: '测试'
    }
    chatList.value.push(welcomeChat.value)
}


// 点击推荐发送
const checkWel = (val) => {
    chatDetail.value = val
    confirmChat('tj')
}
// 新增对话
const addNewChat = () => {
    sessionid = ''
    if (chatList.value && chatList.value[chatList.value.length - 1] && chatList.value[chatList.value.length - 1].type == 'line') return
    chatList.value.push({ type: 'line' })

    if (chatList.value && (chatList.value[0].type !== 'welcome' || chatList.value[0].type == 'line')) return
    chatList.value.push(welcomeChat.value)
}

// 删除对话
const deleteChat = () => {
    chatList.value = []
    sessionid = ''
    chatList.value.push(welcomeChat.value)
}

const closeChat = () => {
    isShowChat.value = false
}

const isFinishType = (res) => {
    const { agentLog } = res
    let a = ''
    // 只有有agentLog且 有info='skip call llm, generate action directly. '才是大模型输出
    if (!agentLog) return 'ok'
    agentLog.forEach(el => {
        if (el.content.info != 'skip call llm, generate action directly. ') {
            a = 'no'
        }
    })
    return a
}

</script>



<style>
.chat-show {
    width: 30px;
    height: 30px;
    position: fixed;
    bottom: 25%;
    right: 0;
    transform: rotateY(180deg);
}

:deep .detail-msg>p {
    margin: 0 !important;
}

:deep .detail-tj>p {
    margin: 0 !important;
}

.demo-loading::after {
    content: "";
    animation: dots 2s infinite steps(3, start);
}

@keyframes dots {
    33.33% {
        content: ".";
    }

    66.67% {
        content: "..";
    }

    100% {
        content: "...";
    }
}

/* 设置滚动条的整体样式 */
::-webkit-scrollbar {
    width: 2px;
    border-radius: 1px;
    /* 设置滚动条的宽度 */
}

/* 设置滚动轨迹的样式 */
::-webkit-scrollbar-track {
    background: #f1f1f1;
    /* 设置滚动轨迹的背景颜色 */
}

/* 设置滚动滑块的样式 */
::-webkit-scrollbar-thumb {
    background: rgba(65, 129, 247, 0.932);
    /* 设置滚动滑块的背景颜色 */
}

.is-agent {
    color: #16a4e6;
    font-size: 14px;
    margin-top: -28px !important;
    margin-left: 10px !important;
}

.detail-msg-active {
    padding: 12px 12px 30px 12px !important;
}


.demo-loading {
    font-size: 16px;
    padding: 12px;
    margin-left: 30PX;
}

p {
    padding: 0;
    margin: 0;
}

.try-question {
    padding: 12px 12px 12px 0;
    font-weight: 600;

}

.try-img {
    width: 16px !important;
    height: 16px !important;
}

.voice-header {
    position: fixed;
    top: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0;
    width: calc(100% - 40px);
    background: #fff;


}

.voice-header p {
    font-size: 20px;
    font-weight: 600;
}

.voice-icons {
    display: flex;


}

.voice-delete {
    margin-right: 10px;
    padding: 0 5px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    border-radius: 50%;


}

:deep .el-icon {
    margin-top: 5px;
}

.voice-delete:hover {
    background: #eee;
}

.voice-content {
    overflow: auto;
    height: calc(100% - 250px);
    margin: 50px 0;


}

.content-msg1 {
    display: flex;
    justify-content: flex-end;
    margin: 20px 0;

}

.content-msg1 img {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-left: 10px;
}


.content-name {
    font-size: 12px;
    color: #ccc;
}

.detail-msg {
    padding: 12px;
    background: rgb(6, 7, 9, 0.04);
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    line-height: 1.5;
    border-radius: 8px;
    margin: 5px 0;
    min-width: 200px;
}

.detail-query {
    padding: 12px;
    background: rgb(148, 152, 247, 0.44);
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    line-height: 1.5;
    border-radius: 8px;
    margin: 5px 0;
}

.detail-tj {
    padding: 12px;
    background: #fff;
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    line-height: 1.5;
    border-radius: 8px;
    margin: 5px 0;
    border: 1px solid rgb(6, 7, 9, 0.04);
}

.detail-tj:hover {
    padding: 12px;
    background: rgb(6, 7, 9, 0.04);
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    line-height: 1.5;
    border-radius: 8px;
    margin: 5px 0;
}

.content-msg {
    display: flex;
    margin: 20px 0;

}

img {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 10px;
}



.content-detail {
    display: flex;
    flex-direction: column;

}

.content-name {
    font-size: 12px;
    color: #ccc;
}

.detail-msg {
    padding: 12px;
    /* // padding: 12px 12px 30px 12px ; */
    background: rgb(6, 7, 9, 0.04);
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    line-height: 1.5;
    border-radius: 8px;
    min-width: 200px;
    margin: 5px 0;
    /* // float: left; */
}

.detail-query {
    padding: 12px;
    background: rgb(148, 152, 247, 0.44);
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    line-height: 1.5;
    border-radius: 8px;
    margin: 5px 0;
}

.detail-tj {
    padding: 12px;
    background: #fff;
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    line-height: 1.5;
    border-radius: 8px;
    margin: 5px 0;
    border: 1px solid rgb(6, 7, 9, 0.04);
    /* // float: left; */
    width: fit-content;
}

.detail-tj:hover {
    padding: 12px;
    background: rgb(6, 7, 9, 0.04);
    font-family: PingFang SC, Noto Sans SC, sans-serif;
    line-height: 1.5;
    border-radius: 8px;
    margin: 5px 0;
}

.new-line {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    margin: 20px 0;

}

.line {
    height: 1px;
    width: 30%;
    box-sizing: border-box;
    border-bottom: 1px solid #ddd;
    margin: 0 10px;
}

.earth-voice {
    padding: 20px;
}

.voice-footer {
    position: fixed;
    width: calc(100% - 40px);
    bottom: 0;
    padding: 20px 0;
    display: flex;
    justify-content: space-between;
    background: #fff;

}

.add-chat {
    margin-right: 20px;
    background: #eee;
    border-radius: 50%;
    padding: 0 8px;
    height: 36px;
    text-align: center;
    line-height: 30px;
    border-radius: 50%;

}

.add-chat img {
    width: 20px;
    height: 20px;
}

:deep .el-icon {
    margin-top: 8px;
}
</style>
